import React, { useState } from 'react';
import { Link, Routes, Route, useNavigate,useLocation } from 'react-router-dom';
import './../style/main.css';
import './../style/kuangjia.css';
import './../style/zhanghu.css';
import logo from '../img/logo.svg'
import avatar from '../img/avatar.jpg'
import Recommend from './online/Recommend';
import Playhall from './online/PlayHall';
import MusicVideo from './online/MusicVideo';
import Favormusic from './mymusic/favormusic';
import Recentplay from './mymusic/recentplay'
import Localmusic from './mymusic/localmusic';
import MusicSearch from './songLists/MusicSearch';
import MusicPlayer from './Player/MusicPlayer';
import Playlist from './songLists/Playlist';
import DayRecommend from './songLists/DayRecommend';
import WelcomIndex from './WelcomeIndex';
import ProfileModal from './tanchuang.jsx/ProfileModal';
import Musiclyric from './Player/musiclyric';
import PlayerLists from './songLists/PlayerLists';

const MusicApp = () => {
  const [showProfile, setShowProfile] = useState(false);
  const [isLyricVisible, setIsLyricVisible] = useState(false);
  const [keyword, setKeyword] = useState('');
  const [songs, setSongs] = useState([]);
  const [currentSong, setCurrentSong] = useState({});
  const [previousPath, setPreviousPath] = useState(null);
  const [loading, setLoading] = useState(false);  // 控制加载状态
  const [curTim, setCurTim] = useState(0);
  const navigate = useNavigate();
  const location = useLocation(); // 获取 location 对象
  const { userId, userNickname } = location.state || {};  //登录页获取到的用户信息
  
  const handleAvatarClick = () => {
    setShowProfile(true);   //打开 ProfileModal
  };
  
  
  const closeProfileModal = () => {
    setShowProfile(false);
  };

  const handleLyricVisibilityChange = (visible) => {
    setIsLyricVisible(visible);
  };

  const handleSearch = async () => {
    setLoading(true);  // 开始加载数据时显示加载动画
    try {
      const response = await fetch(`http://localhost:3000/search?keywords=${keyword}&limit=100`);
      const data = await response.json();

      if (data.result && data.result.songs) {
        const songIds = data.result.songs.map(song => song.id).join(',');
        const detailsResponse = await fetch(`http://localhost:3000/song/detail?ids=${songIds}`);
        const detailsData = await detailsResponse.json();

        if (detailsData.songs) {
          const songsdata = await Promise.all(detailsData.songs.map(async (song) => {
            try {
              const urlResponse = await fetch(`http://localhost:3000/song/url?id=${song.id}`);
              const urlData = await urlResponse.json();

              const playUrl = urlData.data && urlData.data[0] ? urlData.data[0].url : null;

              return {
                musicId: song.id,
                musicName: song.name,
                artName: song.ar[0]?.name || '未知',
                album: song.al.name,
                coverUrl: song.al.picUrl,
                dt: song.dt,
                playUrl: playUrl,
              };
            } catch (urlError) {
              console.error(`Error fetching URL for song ${song.id}: `, urlError);
              return {
                musicId: song.id,
                musicName: song.name,
                artName: song.ar[0]?.name || '未知',
                album: song.al.name,
                coverUrl: song.al.picUrl,
                dt: song.dt,
                playUrl: null,
              };
            }
          }));

          setSongs(songsdata);
          navigate('/musicapp/searchPage');
        } else {
          setSongs([]);
        }
      } else {
        setSongs([]);
      }
    } catch (error) {
      console.error("Error fetching data: ", error);
    } finally {
      setLoading(false);  // 数据加载完成，隐藏加载动画
    }
  };

  const handleKeyDown = (Event) => {
    if (Event.key === 'Enter') {
      handleSearch();
    }
  };

  const handleSongSelect = (song) => {
    setCurrentSong(song);
  };

  const handleBack = () => {
    setPreviousPath(window.location.pathname);
    navigate(-1);
  };

  const handleForward = () => {
    if (previousPath) {
      navigate(previousPath);
    }
  };

  const [playerlisstVisible, setPlayerListVisible] = useState(false)
  const handlePlayerListVisible = () => {
    setPlayerListVisible(!playerlisstVisible);
  }

  return (
    <div className="container">
      <div className='play_menu_btn'>
        <i className="ri-volume-up-line"></i>
        <i className="ri-menu-line"
          onClick={handlePlayerListVisible}
        ></i>
      </div>
      <div className="main-container">
        <div className="left">
          <div className="logo">
            <img src={logo} alt="logo" />
          </div>
          <div className="onlinemusic">
            <div>
              <p>在线音乐</p>
            </div>
            <ul>
              <Link to="recommend"><li><i className="ri-home-line"></i>推荐</li></Link>
              <Link to="playhall/highlights"><li><i className="ri-cup-line"></i>乐馆</li></Link>
              <Link to="musicvideo"><li><i className="ri-mv-line"></i>视频</li></Link>
            </ul>
          </div>
          <div className="mymusic">
            <div>
              <p>我的音乐</p>
            </div>
            <ul>
              <Link to="favormusic/songs"><li><i className="ri-heart-line"></i>喜欢</li></Link>
              <Link to="recentmusic"><li><i className="ri-time-line"></i>最近播放</li></Link>
              <Link to="localmusic"><li><i className="ri-download-2-line"></i>本地和下载</li></Link>
            </ul>
          </div>
          <div className="myplaylists">
            <div>
              <p>收藏歌单</p>
            </div>
            <ul>
              <Link to="recommend/dailysongs"><li><img src="img/liangbo.jpg" alt="img" />梁博</li></Link>
              <Link to={"menu"}><li><img src="img/happy.jpg" alt="img" />快乐</li></Link>
              <li><img src="img/quer.webp" alt="img" />身心安静</li>
              <li><img src="img/oldsong.jfif" alt="img" />老歌</li>
              <li><img src="img/enSong.webp" alt="img" />英文</li>
            </ul>
          </div>
        </div>

        <div className="right">
          <div className="topBar">
            <div className="rh">
              <span className="fowardAndbackon">
                <i className="ri-arrow-left-s-line" onClick={handleBack}></i>
                <i className="ri-arrow-right-s-line" onClick={handleForward}></i>
              </span>
              <div className="seh">
                <div className="search">
                  <i className="ri-search-line"></i>
                  <input
                    type="text"
                    id="searchsongs"
                    placeholder="搜索"
                    value={keyword}
                    onChange={(e) => setKeyword(e.target.value)}
                    onKeyDown={handleKeyDown} />
                </div>
                <span className="listhen"><i className="ri-music-fill"></i></span>
              </div>
            </div>
            <div className="lef">
              <div className="avatar" onClick={handleAvatarClick}>
                <img src={avatar} alt="" />
              </div>
              {showProfile && (
                  <ProfileModal
                      onClose={closeProfileModal}
                      isVisible={showProfile}
                      userId={userId} // 传递 userId
                      userNickname={userNickname} // 传递 userNickname
                  />
              )}
              <div className="name">
                <p>Denselin</p>
              </div>
            </div>
          </div>

          <div className="ma">
            {/* 添加加载动画 */}
            {loading ? (<div className="loadingPage">
              <div className="loadcomponents">
                <div className='loader2'></div>
                <div className='loader1'></div>
              </div>
            </div>) : (
              <Routes>
                <Route path='/' element={<WelcomIndex />} />
                <Route path="recommend/*" element={<Recommend />} />
                <Route path="recommend/:playlistId" element={<Playlist onSongSelect={handleSongSelect} />} />
                <Route path='recommend/dailysongs' element={<DayRecommend onSongSelect={handleSongSelect} />} />
                <Route path="playhall/*" element={<Playhall />} />
                <Route path="playhall/highlights/:playlistId" element={<Playlist onSongSelect={handleSongSelect} />} />
                <Route path="musicvideo" element={<MusicVideo />} />
                <Route path="favormusic/*" element={<Favormusic />} />
                <Route path='recentmusic' element={<Recentplay />} />
                <Route path="localmusic/*" element={<Localmusic />} />
                <Route path="searchPage" element={<MusicSearch songs={songs} onSongSelect={handleSongSelect} />} />
              </Routes>
            )}

          </div>
        </div>
      </div>
      {isLyricVisible && <Musiclyric
        currentSong={currentSong} curTim={curTim}
        isLyricVisible={isLyricVisible}
        onLyricVisibilityChange={handleLyricVisibilityChange}
      />}
      {playerlisstVisible && <PlayerLists />}
      <MusicPlayer
        currentSong={currentSong}
        setCurTim={setCurTim}
        isLyricVisible={isLyricVisible}
        onLyricVisibilityChange={handleLyricVisibilityChange}
      />
    </div>
  );
};

export default MusicApp;
